package com.usermanage.controller;

import com.contract.Bean.ContractBean1;
import com.contract.Common.ContractIOC;
import com.google.common.collect.Lists;
import com.ordercore.Util.ResponseData.ResponseData;
import com.usermanage.ExceptionConfig.MyException;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.*;
import com.usermanage.beanParam.*;

import com.usermanage.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.collections.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 前台选装
 */
@Slf4j
@RestController
@RequestMapping("/shopping")
public class ShoppingController {

    @Resource
    private ContractService contractService;

    @Resource
    private OrderService orderService;

    @Resource
    private CompanyService companyService;

    @Resource
    private UserService userService;

    @Resource
    private ContractRealTimePriceService contractRealTimePriceService;

    /**
     * 企业首页
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/index.page", method = RequestMethod.GET)
    public ModelAndView list() throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("1".equals(userDetail.getCompany_id())) {
            mv.addObject("url",StaticUtil.SKUIP);
            mv.setViewName("/index/index");
        } else {
            mv.addObject("userName", userDetail.getUsername());
            ContractBean1 contractBean1 = new ContractBean1();
            contractBean1.setCompanyB_id(userDetail.getCompany_id());
            ResponseData responseData = ContractIOC.findOne(contractBean1);
            if (responseData.isRet()) {
                ContractBean1 contractBean11 = (ContractBean1) responseData.getData();
                mv.addObject("contract_id", contractBean11.getId());
                mv.addObject("priceSummaryId", contractBean11.getTablePrice_id());
                mv.addObject("companyName", contractBean11.getPartyB());
                mv.setViewName("/shopping/indexRealTime");
            } else {
                mv.setViewName("forward:/index.page");
            }
        }
        return mv;
    }

    /**
     * 添加购物车
     *
     * @param order
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public JsonData addOrderCar(String order) throws Exception {
        List<Map> list = StringUtil.JsonToList(order);
        for (Map map : list) {

            map.put("purNum", 1);
            map.put("sku_remark", "无");
            OrderBean bean = new OrderBean();
            bean.setSku_code(String.valueOf(map.get("sku_code")));
            bean.setUser_id(String.valueOf(SpringSecurityUtils.getCurrentUser().getId()));
            List<OrderBean> orderBeans = orderService.findAll(bean);
            if (orderBeans.size() > 0) {
                for (OrderBean orderBean : orderBeans) {
                    Map sku = StringUtil.JsonToMap(orderBean.getOrder_sku());
                    int purNum = Integer.valueOf(sku.get("purNum").toString());
                    sku.put("purNum", purNum + 1);
                    sku.put("sku_remark", "无");
                    orderBean.setOrder_sku(StringUtil.ObjectToJson(sku));
                    orderService.save(orderBean);
                }
            }
            //验证该sku是否存在。
            boolean bool = orderService.isExisit(bean);
            if (!bool) {
                bean.setPrice(String.valueOf(map.get("sku_contract_price")));
                bean.setOrder_sku(StringUtil.ObjectToJson(map));
                orderService.save(bean);
            }
        }
        return JsonData.success();
    }

    /**
     * 购物车界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/shopcar.page", method = RequestMethod.GET)
    public ModelAndView orderList() throws Exception {
        ModelAndView mv = new ModelAndView();
        OrderBean bean = new OrderBean();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        bean.setUser_id(String.valueOf(userDetail.getId()));
        mv.addObject("userName", userDetail.getUsername());
        List<OrderBean> list = orderService.findAll(bean);
        List<Map> listMap = new ArrayList<>();
        for (OrderBean resultBean : list) {
            Map map = StringUtil.JsonToMap(resultBean.getOrder_sku());
            if (!map.containsKey("arriveTime")) {
                map.put("arriveTime", DateUtil.getNowDayString());
            }
            map.put("order_id", resultBean.getId());
            if (StringUtils.isBlank((String) map.get("sku_slug_set")) || map.get("sku_slug_set") == null) {
                map.put("sku_slug_set", "无");
            }
            listMap.add(map);
        }
        mv.addObject("list", listMap);
        mv.setViewName("/shopping/shopCar");
        return mv;
    }

    /**
     * 订单数量发生改变时更改购物车信息
     *
     * @param price
     * @param sku_code
     * @param purNum
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateOrderCar.json", method = RequestMethod.POST)
    public JsonData updateOrderCar(String sku_remark, String price, String sku_code, String purNum, String
            arriveTime) throws Exception {
        if (StringUtils.isBlank(purNum) || StringUtils.isBlank(sku_code) || StringUtils.isBlank(arriveTime) || StringUtils.isBlank(sku_remark)) {
            return JsonData.fail("提交数据异常");
        }
        String[] nums = purNum.split(",");
        String[] codes = sku_code.split(",");
        String[] times = arriveTime.split(",");
        String[] remarks = sku_remark.split(",");
        if ((nums.length != codes.length) || (codes.length != times.length) || (remarks.length != codes.length)) {
            return JsonData.fail("提交数据异常");
        }
        OrderBean bean = new OrderBean();
        bean.setUser_id(String.valueOf(SpringSecurityUtils.getCurrentUser().getId()));
        List<OrderBean> list = orderService.findAll(bean);
        for (OrderBean resultBean : list) {
            Map map = StringUtil.JsonToMap(resultBean.getOrder_sku());
            for (int i = 0; i < nums.length; i++) {
                if (codes[i].equals(String.valueOf(map.get("sku_code")))) {
                    map.put("purNum", nums[i]);
                    map.put("sku_remark", remarks[i]);
                    map.put("arriveTime", times[i]);
                    break;
                }
            }
            map.put("order_id", resultBean.getId());
            resultBean.setPrice(price);
            resultBean.setOrder_sku(StringUtil.ObjectToJson(map));
            orderService.save(resultBean);
        }
        return JsonData.success();
    }

    /**
     * 订单地址界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/address.page", method = RequestMethod.GET)
    public ModelAndView address(String price) throws Exception {
        ModelAndView mv = new ModelAndView();
            mv.addObject("userName", SpringSecurityUtils.getCurrentUser().getUsername());
        mv.addObject("company_id", SpringSecurityUtils.getCurrentUser().getCompany_id());
        mv.addObject("price", price);
        mv.addObject("group_id", StaticUtil.GONGYINGLIANGROUP);
        mv.setViewName("/shopping/address");
        return mv;
    }


    @RequestMapping(value = "/delOrderCarSkuById.json", method = RequestMethod.POST)
    public JsonData delOrderCarSkuById(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            return JsonData.fail("提交数据异常");
        }
        Optional<OrderBean> optional = orderService.findById(Integer.valueOf(id));
        if (!optional.isPresent()) {
            return JsonData.fail("商品已被移除，请检查订单。");
        }
        orderService.delete(optional.get());
        return JsonData.success();
    }

}
